package com.sise.rsc.service;

import com.sise.rsc.entity.*;
import com.sise.rsc.repository.CourierRepository;
import com.sise.rsc.repository.CourierStatusRepository;
import com.sise.rsc.repository.PackageActionRepository;
import com.sise.rsc.repository.TaskRepository;
import com.sise.rsc.util.CacheUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class TaskService {



    @Resource
    private CourierRepository courierRepository;
    @Resource
    private CourierStatusRepository courierStatusRepository;
    @Resource
    private PackageActionRepository packageActionRepository;
    @Resource
    private TaskRepository taskRepository;
    /**
     * 分配包裹任务
     * @param aPackage
     * @param taskName "取件"or"派件"
     * @return
     */
    public boolean AssignTasks(APackage aPackage,String taskName){

        //获取今天工作状态为正常的员工
        List<Courier> workingCouriers = new LinkedList<>();
        List<CourierStatus> statuses = courierStatusRepository.findCourierStatusesByStatusAndTime("正常",new Date());
        for (CourierStatus status : statuses) {
            workingCouriers.add(status.getCourier());
        }
        //未找到符合条件员工，分配失败
        if (workingCouriers.isEmpty())
            return false;
        //获取与包裹地址匹配的员工
        List<Courier> workingAddressCouriers = new LinkedList<>();
        String address = "";
        if (taskName.equals("取件")){
            address = aPackage.getSendAddress();
        }else {
            address = aPackage.getReceiptAddress();
        }
        for (Courier workingCourier : workingCouriers) {
            if (address.indexOf(workingCourier.getWorkingArea().getAddressName()) != -1){
                System.out.println("workingAddressCouriers-备选快递员："+workingCourier.getNo());
                workingAddressCouriers.add(workingCourier);
            }
        }

        if (workingAddressCouriers.isEmpty())   //未找到符合条件员工，分配失败
            return false;
        else if (workingAddressCouriers.size() == 1){ //符合条件员工只有一个，直接分配
            //添加到任务表
            Task task = new Task();
            task.setTaskName(taskName);
            task.setCourier(workingAddressCouriers.get(0));
            task.setaPackage(aPackage);
            task.setCreateTime(new Date());
            task.setState(1);
            addTask(task);

            PackageAction packageAction = new PackageAction();
            packageAction.setaPackage(aPackage);
            packageAction.setCourier(workingAddressCouriers.get(0));
            packageAction.setState(aPackage.getState());
            packageAction.setTime(new Date());

            if (taskName.equals("取件")){
                packageAction.setAction("快递员【"+workingAddressCouriers.get(0).getRealName()+"】正在准备上门取件");
            }else {
                packageAction.setAction("快递员【"+workingAddressCouriers.get(0).getRealName()+"】正在准备派件");
            }
            packageActionRepository.save(packageAction);
            return true;
        }else {  //符合条件员工有多个时，根据员工的工作量分配任务，任务少的快递员优先分配任务

            Courier target = workingAddressCouriers.get(0);
            int minTask = 10000000;
            for (Courier c : workingAddressCouriers) {
                //某快递员的任务数(包括：1:未处理，0:派件成功),除：2：未完成
                int num = taskRepository.findAllByCourierNoAndNoState(c.getNo(),2).size();
                System.out.println(c.getNo()+":"+num);
                if (num<minTask){
                    minTask = num;
                    target = c;
                }
            }
            //分配任务
            //添加到任务表
            Task ta = new Task();
            ta.setTaskName(taskName);
            ta.setCourier(target);
            ta.setaPackage(aPackage);
            ta.setCreateTime(new Date());
            ta.setState(1);
            addTask(ta);

            PackageAction packageAction = new PackageAction();
            packageAction.setaPackage(aPackage);
            packageAction.setCourier(workingAddressCouriers.get(0));
            packageAction.setState(aPackage.getState());
            packageAction.setTime(new Date());

            if (taskName.equals("取件")){
                packageAction.setAction("快递员【"+workingAddressCouriers.get(0).getRealName()+"】正在准备上门取件");
            }else {
                packageAction.setAction("快递员【"+workingAddressCouriers.get(0).getRealName()+"】正在准备派件");
            }
            packageActionRepository.save(packageAction);

            return true;

        }

    }

    public List<Task> findAllByCourierNoAndNoState(String no,int state){
        return taskRepository.findAllByCourierNoAndNoState(no,state);
    }

    /**
     * 判断地址是否未可自动分配
     * @param address
     * @return
     */
    public boolean isCanAutoAssignTasks(String address){
        List<Courier> couriers = courierRepository.findCouriersByWorkingAreaAddressNameLike("%" + address + "%");
        if (couriers.isEmpty())
            return false;
        else
            return true;

    }
    public void addTask(Task task){
        taskRepository.save(task);
    }

    public Task findTaskByTaskNameAndAPackageNo(String taskName,String no){
        return taskRepository.findTaskByTaskNameAndAPackageNo(taskName,no);
    }

    public Task findTaskByTaskNameAndStateAndAPackageNo(String pNo ,int state,String taskName){
        return taskRepository.findTaskByTaskNameAndStateAndAPackageNo(pNo ,state,taskName);
    }



    public void updateTaskState(int state,String taskName,int pId,int cId){
        taskRepository.updateTaskState(state, taskName, pId, cId);
    }

    public List<Task> findAllTaskByState(){
        return taskRepository.findAllTaskByState();
    }
    public int findAllTaskByStateAndcId(int cId){
        return taskRepository.findAllTaskByStateAndcId(cId);
    }

    public int findTaskSumByTaskNameAndPackageId(String taskName,int pId){
        return taskRepository.findTaskSumByTaskNameAndPackageId(taskName,pId);
    }
}
